// pages/my/my.js
const app = getApp();
const baseUrl = app.getApiBaseUrl();

console.log('getApp available:', typeof getApp !== 'undefined');
Page({
  data: {
    userInfo: {
      name: '',
      inviteCode: '',
      token: null,
      dailyTokenRemaining: null,
      remainingToken: 15000,
      invitedBy: '',
      role: '',
      stageGoals: [],
      language: 'zh-CN',
      displayLanguage: '简体中文',
      avatar: '',
      nickname: '',
      mobile: ''
    },
    unionID: '',
    membershipStatus: '未开通',
    currentGoal: '未设置',
    membershipExpiryDate: '',
    isProfileComplete: false
  },

  onLoad() {
    console.log('App instance:', app.globalData);
    this.loadUserInfo();
  },

  onShow() {
    const unionID = app.globalData.unionID || wx.getStorageSync('unionID');
    this.setData({ unionID });
    this.loadUserInfo();
  },

  loadUserInfo() {
    const openID = wx.getStorageSync('openID');
    const jwt_token = wx.getStorageSync('jwt_token');
    if (!openID || !jwt_token) {
      console.log('loadUserInfo: openID 或 token 缺失，尝试静默登录');
      this.handleUnauthorized();
    } else {
      app.globalData.openID = openID;
      app.globalData.jwtToken = jwt_token;
      this.fetchUserInfo();
      this.checkProfileCompletion();
    }
  },

  checkProfileCompletion() {
    const jwt_token = wx.getStorageSync('jwt_token');
    const openID = wx.getStorageSync('openID');

    if (!openID || !jwt_token) {
        console.log('checkProfileCompletion: openID 或 jwt_token 缺失');
        this.handleUnauthorized();
        return;
    }

    wx.request({
      url: `${baseUrl}/user/check-profile-completion`,
        method: 'GET',
        header: { 'Authorization': `Bearer ${jwt_token}` },
        data: { openID },
        success: (res) => {
            if (res.statusCode === 200) {
              this.setData({ isProfileComplete: res.data.isComplete });
              if (!res.data.isComplete) {
                  const fieldMap = {
                      name: '姓名',
                      avatar: '头像',
                      gender: '性别',
                      province: '地区'
                  };
                  const missing = res.data.missingFields.map(f => fieldMap[f]).join('、');
                  wx.showToast({
                      title: `请完善${missing}`,
                      icon: 'none',
                      duration: 2000
                  });
              }
            } else {
                console.error('检查完善状态失败:', res);
                wx.showToast({ title: '检查完善状态失败', icon: 'none' });
            }
        },
        fail: (err) => {
            console.error('检查用户信息完善状态失败:', err);
            wx.showToast({ title: '网络错误', icon: 'none' });
        }
    });
},

  fetchUserInfo() {
    const jwt_token = wx.getStorageSync('jwt_token');
    const openID = wx.getStorageSync('openID');

    if (!openID || !jwt_token) {
      console.log('fetchUserInfo: openID 或 jwt_token 缺失，尝试静默登录');
      this.handleUnauthorized();
      return;
    }

    wx.request({
      url: `${baseUrl}/user/settings`,
      method: 'GET',
      header: {
        'Cache-Control': 'no-cache',
        'Authorization': `Bearer ${jwt_token}`
      },
      data: { openID },
      success: (res) => {
        if (res.statusCode === 200 && res.data) {
          const roleMap = {
            'junior_student': '初中生',
            'high_school_student': '高中生',
            'postgraduate_exam': '考研er',
            'civil_service_exam': '考公务员',
            'job_seeker_or_professional': '职场人',
            'lifelong_learner': '终身学习者'
          };
          const role = roleMap[res.data.role] || res.data.role || '未设置';

          const stageGoals = res.data.stageGoals || [];
          const latestGoal = stageGoals.length > 0
            ? stageGoals.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))[0].goal
            : '未设置';

          const memberships = res.data.memberships || [];
          let membershipExpiryDate = '未开通';
          const activeMemberships = memberships.filter(m => m.expiryTime && m.expiryTime > Date.now());
          if (activeMemberships.length > 0) {
            const latestMembership = activeMemberships.reduce((latest, current) =>
              current.expiryTime > latest.expiryTime ? current : latest
            );
            const date = new Date(latestMembership.expiryTime);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            membershipExpiryDate = `${year}年${month}月${day}日`;
          }

          this.setData({
            'userInfo.name': res.data.name || '微信用户',
            'userInfo.inviteCode': res.data.inviteCode || wx.getStorageSync('inviteCode') || '新用户默认邀请码',
            'userInfo.remainingToken': res.data.availableTokens !== undefined ? res.data.availableTokens : 15000,
            'userInfo.role': role,
            'userInfo.stageGoals': stageGoals,
            'userInfo.language': res.data.language || 'zh-CN',
            'userInfo.displayLanguage': res.data.language === 'zh-CN' ? '简体中文' : 'English',
            'userInfo.avatar': res.data.avatar || '',
            'userInfo.nickname': res.data.nickname || res.data.name || '',
            'userInfo.mobile': res.data.mobile || '',
            currentGoal: latestGoal,
            membershipExpiryDate: membershipExpiryDate,
            membershipStatus: activeMemberships.length > 0 ? '已开通' : '未开通'
          });

          if (res.data.inviteCode) {
            wx.setStorageSync('inviteCode', res.data.inviteCode);
          }
          if (res.data.jwt_token) {
            wx.setStorageSync('jwt_token', res.data.jwt_token);
          }
        } else if (res.statusCode === 401) {
          console.log('fetchUserInfo: 401 Unauthorized，尝试重新登录');
          wx.removeStorageSync('jwt_token');
          this.handleUnauthorized();
        } else {
          console.error('fetchUserInfo 失败:', res);
          wx.showToast({ title: `数据加载失败: ${res.statusCode}`, icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('fetchUserInfo 请求失败:', err);
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },

  handleUnauthorized() {
    wx.showLoading({ title: '加载中...' });
    app.doAutoLogin(true)
      .then(() => {
        wx.hideLoading();
        const openID = wx.getStorageSync('openID');
        const jwt_token = wx.getStorageSync('jwt_token');
        if (openID && jwt_token) {
          app.globalData.openID = openID;
          app.globalData.jwtToken = jwt_token;
          this.setData({ unionID: wx.getStorageSync('unionID') });
          console.log('静默登录成功，重新获取用户信息');
          this.loadUserInfo();
        } else {
          throw new Error('静默登录后仍未获取到 openID 或 jwt_token');
        }
      })
      .catch((err) => {
        wx.hideLoading();
        console.error('静默登录失败:', err);
        wx.showModal({
          title: '登录失败',
          content: '请重新登录以继续使用',
          confirmText: '重新登录',
          cancelText: '取消',
          success: (res) => {
            if (res.confirm) {
              app.doAutoLogin(true);
            }
          }
        });
      });
  },

  goToProfile() {
    wx.navigateTo({
      url: '/pages/profile/profile'
    });
  },

  goToMembershipPurchase() {
    wx.navigateTo({ url: '/pages/membership-purchase/membership-purchase' });
  },

  goToLearningRecords() {
    wx.switchTab({ url: '/pages/conversationHistory/conversationHistory' });
  },

  goToFeedback() {
    wx.navigateTo({ url: '/pages/feedback/feedback' });
  },

  goToGoalEdit() {
    wx.navigateTo({ url: '/pages/goal/goal' });
  },
  goToAnalyzeImageHistory() {
        wx.navigateTo({
          url: '/pages/analyzeImageHistory/analyzeImageHistory',
          success: () => console.log('跳转到 analyzeImageHistory 页面成功'),
          fail: (err) => console.error('跳转失败:', err)
        });
  }
  
});